package com.liit.controller.weixin.controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.liit.entity.CodeFormMap;
import com.liit.entity.OrgInfoFormMap;
import com.liit.entity.PartyAttendFormMap;
import com.liit.entity.PartyFormMap;
import com.liit.entity.PartySignFormMap;
import com.liit.entity.UserFormMap;
import com.liit.entity.UserRoleFormMap;
import com.liit.entity.WeixinUserFormMap;
import com.liit.exception.WeixinException;
import com.liit.mapper.CodeMapper;
import com.liit.mapper.OrgInfoMapper;
import com.liit.mapper.PartyAttendMapper;
import com.liit.mapper.PartyMapper;
import com.liit.mapper.UserMapper;
import com.liit.mapper.WeixinUserMapper;
import com.liit.plugin.PageView;
import com.liit.upload.UploadUtil;
import com.liit.util.AssertHelper;
import com.liit.util.Common;
import com.liit.util.DictUtils;
import com.liit.util.PasswordHelper;
import com.liit.util.RegionUtils;

/**
 * 
 * @author dingweibo
 * @Title: OrganController.java
 * @Description: 机构注册
 * @date 2016年3月31日
 */
@Controller
@RequestMapping("weixin/organ")
public class OrganController extends WeixinMenuController {
	@Resource
	private OrgInfoMapper orgInfoMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private PartyMapper partyMapper;
	@Resource
	private PartyAttendMapper partyAttendMapper;
	@Resource
	private CodeMapper codeMapper;
	@Resource
	private WeixinUserMapper weixinUserMapper;
	/**
	 * 机构注册页
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/regist/index")
	public String registIndex(Model model) throws Exception {
		return org_reg(model);
	}
	/**
	 * 机构注册
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	@RequestMapping("/regist/organRegister")
	public String registRegister(Model model, RedirectAttributes redirectAttributes) throws Exception {
		
		// ---------------- 获取提交的机构信息
		OrgInfoFormMap orgInfoFormMap = getFormMap(OrgInfoFormMap.class);
		
		//----------------- 获取提交的管理账号信息
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		
		//----------------- 注册
		register(userFormMap, orgInfoFormMap, Common.USER_REG_TYPE_ORG,null);
		
		//----------------- 设置跳转页面msg信息
		return doMsg(null, null, null, getContextPath() + "/weixin/org/myinfo.shtml", null, null, null, null, null, redirectAttributes);
	}
	
	/**
	 * 邀请码注册
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	@RequestMapping("/regist/codeRegister")
	public String registCodeRegister(Model model, RedirectAttributes redirectAttributes) throws Exception {
		
		//-------------------- 获取邀请码及邀请码对应机构信息
		CodeFormMap codeFormMap = getOne(codeMapper.findByNames(getFormMap(CodeFormMap.class)));
		AssertHelper.notEmpty(codeFormMap, "未找到邀请码,请确认邀请码是否填写正确");
		AssertHelper.empty(codeFormMap.getStr("useOpenid"), "邀请码已使用,请更换其它邀请码");
		
		//------------------- 更新邀请码的使用人
		codeFormMap.put("useOpenid", getWeixinUserInfo().getStr("openid"));
		codeMapper.editEntity(codeFormMap);
		
		//------------------- 获取邀请码对应机构ID
		OrgInfoFormMap params = new OrgInfoFormMap();params.put("id", codeFormMap.getInt("orgInfoId"));
		OrgInfoFormMap orgInfoFormMap = getOne(orgInfoMapper.findByNames(params));
		
		//-------------------- 获取提交的管理账号信息
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		
		//-------------------- 注册
		register(userFormMap, orgInfoFormMap, Common.USER_REG_TYPE_CODE,codeFormMap.getStr("code"));
		
		//------------------- 设置跳转页面msg信息
		return doMsg(null, null, null, getContextPath() + "/weixin/org/myinfo.shtml", null, null, null, null, null, redirectAttributes);
	}
	/**
	 * 添加管理用户 
	 * @param userFormMap 管理端账户信息
	 * @param orgInfoFormMap 机构信息
	 * @param regtype 注册类型，机构注册/邀请码注册
	 * @param code 邀请码
	 * @throws Exception 
	 */
	private void register(UserFormMap userFormMap,OrgInfoFormMap orgInfoFormMap,Integer regtype, String code ) throws Exception{
		
		//--------------------- 如果为机构注册
		if(regtype.equals(Common.USER_REG_TYPE_ORG)){
			OrgInfoFormMap orgInfo = getOrgInfo();
			if (orgInfo != null && orgInfo.getInt("status") != Common.ORG_STATUS_REJECT) {
				throw new WeixinException("不允许重复申请机构");
			}
			// ---------------- 保存机构信息
			orgInfoFormMap.put("openid", getOpenid());
			orgInfoMapper.addEntity(orgInfoFormMap);
		}
		//-------------------- 验证管理用户是否已经存在
		UserFormMap params = new UserFormMap();params.put("accountName", userFormMap.get("accountName"));
		UserFormMap oldUserFormMap = getOne(userMapper.findByNames(params));
		AssertHelper.empty(oldUserFormMap, "管理账户已存在，请更换管理账号");
		//-------------------- 设置管理端用户信息
		userFormMap.put("userName", getWeixinUserInfo().getStr("nickname"));
		userFormMap.put("description", getWeixinUserInfo().getStr("nickname"));
		userFormMap.put("locked", (regtype.equals(Common.USER_REG_TYPE_ORG) ? 1 : 0));
		userFormMap.put("createTime", new Timestamp(System.currentTimeMillis()));
		userFormMap.put("deletestatus", (regtype.equals(Common.USER_REG_TYPE_CODE) ? 0 : 1));
		userFormMap.put("province", orgInfoFormMap.getStr("province"));
		userFormMap.put("city", orgInfoFormMap.getStr("city"));
		userFormMap.put("area", orgInfoFormMap.getStr("area"));
		userFormMap.put("street", orgInfoFormMap.getStr("street"));
		userFormMap.put("openid", getWeixinUserInfo().getStr("openid"));
		//-------------------- 加密管理端密码
		PasswordHelper passwordHelper = new PasswordHelper();
		passwordHelper.encryptPassword(userFormMap);
		logger.info(userFormMap.toString());
		//------------------- 保存管理账号信息
		userMapper.addEntity(userFormMap);
		
		//------------------- 邀请码注册时
		if(regtype.equals(Common.USER_REG_TYPE_CODE)){
			//------------------- 权限分配
			UserRoleFormMap userRoleFormMap = new UserRoleFormMap();
			userRoleFormMap.put("userId", userFormMap.get("id"));
			userRoleFormMap.put("roleId", 3);
			userMapper.addEntity(userRoleFormMap);
		}
		
		//------------------- 更新微信用户信息
		WeixinUserFormMap weixinUserFormMap = getWeixinUserInfo();
		weixinUserFormMap.put("regType", regtype);
		weixinUserFormMap.put("orgInfoId", Integer.parseInt(orgInfoFormMap.get("id").toString()));
		if(regtype.equals(Common.USER_REG_TYPE_CODE))
			weixinUserFormMap.put("code", code);
		weixinUserMapper.editEntity(weixinUserFormMap);
		//weixinUserMapper.editEntity(weixinUserFormMap);
	}
	
	private<T> T getOne(List<T> list){
		if(list == null || list.isEmpty()){
			return null;
		}
		return list.get(0);
	}
	/**
	 * 发布活动首页
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	@RequestMapping("/party/index")
	public String partyIndex(Model model) throws Exception {
		
		return org_apply(model);
	}
	/**
	 * 发布活动
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	@RequestMapping("/party/apply")
	public String partyPostParty(Model model, RedirectAttributes redirectAttributes, MultipartHttpServletRequest request) throws Exception {
		//----------------- 获取提交的活动信息
		PartyFormMap partyFormMap = getFileFormMap(PartyFormMap.class, request);
		
		//----------------- 上传图片
		UploadUtil.uploadImage((Map<String, MultipartFile>) partyFormMap.get("FILES"), UploadUtil.UPLOAD_PATH + "party");
		
		// ---------------- 设置活动信息
		partyFormMap.put("createTime", new Timestamp(System.currentTimeMillis()));
		partyFormMap.put("openid", getWeixinUserInfo().getStr("openid"));
		partyFormMap.put("orgInfoId", getWeixinUserInfo().getInt("orgInfoId"));
		partyFormMap.put("status", 0);
		// ---------------- 保存活动信息
		partyMapper.addEntity(partyFormMap);
		partyFormMap.put("codeNo", Common.format(new Date(), "yyyy") + String.format("%05d", partyFormMap.get("id")));
		partyFormMap.put("detail", partyFormMap.getStr("detail").replace("待生成",partyFormMap.getStr("codeNo")));
		partyMapper.editEntity(partyFormMap);
		//----------------- 设置跳转页面msg信息
		return doMsg(null, null, null, getContextPath() + "/weixin/org/myparty.shtml", null, null, null, null, null, redirectAttributes);
	}
	/**
	 * 活动详情
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/party/detail")
	public String partyDetail(Model model) throws Exception {
		String partyId = getPara("partyId");
		PartyFormMap partyFormMap = new PartyFormMap();
		partyFormMap.put("id", partyId);
		List<PartyFormMap> result = partyMapper.findByNames(partyFormMap);
		if(result.size()>0){
			PartyFormMap record = result.get(0);
			record.put("province", RegionUtils.getRegionNameById(record.getStr("province")));
			record.put("city", RegionUtils.getRegionNameById(record.getStr("city")));
			record.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
			record.put("street", RegionUtils.getRegionNameById(record.getStr("street")));
			record.put("type", DictUtils.getDictByValue("PARTY_TYPE", record.getInt("type")).get("label"));
			model.addAttribute(record);
		} else {
			throw new WeixinException("无此活动");
		}
		model.addAttribute("signs", mapper.findByAttribute("partyId", partyId, PartySignFormMap.class).size());
		
		// 使用jssdk
		HttpServletRequest request = getHttpServletRequest();
		useJSSDK(request.getRequestURL().toString() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
		
		return org_party_detail(model);
	}
	/**
	 * 获取活动评价
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/party/getComment")
	public PageView getComments(Model model){
		PartyAttendFormMap partyAttendFormMap = new PartyAttendFormMap();
		AssertHelper.notEmpty(getPara("partyId"), "参数partyId找不到");
		partyAttendFormMap.put("partyId", getPara("partyId"));
		partyAttendFormMap.put("status", 1);
		List<Map> records = partyAttendMapper.findPartyAttendPage(toFormMap(partyAttendFormMap, getPara("pageNo"), getPara("pageSize"), "order by commentTime desc"));
		pageView.setRecords(records);
		return pageView;
	}
	/**
	 * 获取活动参与人
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/party/getAttend")
	public PageView getAttend(Model model){
		PartyAttendFormMap partyAttendFormMap = new PartyAttendFormMap();
		AssertHelper.notEmpty(getPara("partyId"), "参数partyId找不到");
		partyAttendFormMap.put("partyId", getPara("partyId"));
		List<Map> records = partyAttendMapper.findPartyAttendPage(toFormMap(partyAttendFormMap, getPara("pageNo"), getPara("pageSize"), "order by createTime desc"));
		pageView.setRecords(records);
		return pageView;
	}
	
	/**
	 * 获取活动报名人
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/party/getSign")
	public PageView getSign(Model model){
		PartySignFormMap partySignFormMap = new PartySignFormMap();
		AssertHelper.notEmpty(getPara("partyId"), "参数partyId找不到");
		partySignFormMap.put("partyId", getPara("partyId"));
		List<Map> records = partyAttendMapper.findPartySignPage(toFormMap(partySignFormMap, getPara("pageNo"), getPara("pageSize"), "order by createTime desc"));
		pageView.setRecords(records);
		return pageView;
	}
	
	@ResponseBody
	@RequestMapping("/edit")
	@Transactional(readOnly=false)
	public Object edit() {
		try {
			OrgInfoFormMap record = getFormMap(OrgInfoFormMap.class);
			OrgInfoFormMap orgInfo = orgInfoMapper.findbyFrist("id", record.get("id").toString(), OrgInfoFormMap.class);
			AssertHelper.notEmpty(orgInfo, "没有找到机构信息");
			if (!getWeixinUserInfo().getInt("orgInfoId").equals(orgInfo.getInt("id"))) {
				throw new WeixinException("您不属于当前机构");
			}
			orgInfoMapper.editEntity(record);
			return "success";
		} catch (Exception e) {
			logger.error("修改机构信息失败", e);
		}
		return "error";
	}

	public static void main(String[] args) {
		System.out.println();
	}
}
